package com.dzl.ocr;

import com.dzl.base.controller.BaseController;
import com.dzl.util.EmptyUtils;
import com.dzl.util.JsonResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 对接百度的OCR - 控制层
 * @author WangJian
 * @date 2021/7/17 0017
 */
@RequestMapping("baiduOcr")
@RestController
public class BaiduOcrController extends BaseController {

    /**
     *
     * @date 2021/7/17 0017 11:25
     * @author wangjian
     * @param image
     * @return com.dzl.util.JsonResult
     */
//    @PostMapping("getOcr")
//    public JsonResult<List<String>> getOcr(@RequestBody String image){
//        String accessToken = BaiduOcrUtils.getOCRAccessToken(BaiduOcrConstant.API_KEY, BaiduOcrConstant.SECRET_KEY);
//        List<String> list = BaiduOcrUtils.generalBasicOCR(image, accessToken);
//        return JsonResult.success(list);
//    }

    /**
     *
     * @date 2021/7/17 0017 11:25
     * @author wangjian
     * @param image 图片路径
     * @return com.dzl.util.JsonResult
     */
    @PostMapping("getOcr")
    public JsonResult<List<String>> getOcr(String image){
        if (EmptyUtils.isEmpty(image)){
            return JsonResult.failWithMsg("请先传入图片");
        }
        String accessToken = BaiduOcrUtils.getOCRAccessToken(BaiduOcrConstant.API_KEY, BaiduOcrConstant.SECRET_KEY);
        List<String> list = BaiduOcrUtils.generalBasicOCR(image, accessToken);
        List<String> pwds = new ArrayList<>();
        if (EmptyUtils.isNotEmpty(list)){
            list.forEach(x ->{
                if (x.startsWith("密码:")){
                    String[] split = x.substring(3).split("-");
                    if (split.length == 4){
                        for (String str : split) {
                            pwds.add(str);
                        }
                    }
                }else if (x.startsWith("FL")){
                    String[] split = x.split("-");
                    if (split.length == 4){
                        for (String str : split) {
                            pwds.add(str);
                        }
                    }
                }
            });
        }
        if (EmptyUtils.isEmpty(pwds)){
            return JsonResult.failWithMsg("密码识别有误，请重新扫码");
        }
        return JsonResult.success(pwds);
    }
}
